import java.util.*;
import akka.actor.*;

/**
 * 
 * @author Pietro Bua & Rohmin Mirza
 *
 */
public class Leader extends UntypedActor
{
	private boolean available;
	private ActorRef secretary;
	private ArrayList<ActorRef> meeting;
	private int arrived = 0;
	private int inMeeting = 0;
	
	/**
	 * 
	 */
	@Override
	public void preStart()
	{
		System.out.println("Leader has started");
	}
	
	/**
	 * 
	 */
	@Override
	public void onReceive(Object message) throws Exception
	{
		if( message instanceof CustomerMeeting )
		{
			secretary = getSender();
			System.out.println("Customer requests meeting");
			CustomerMeeting cm = (CustomerMeeting) message;
			meeting = cm.getCustomers();
			meeting.add(cm.getDeveloper());
			for (ActorRef m : meeting) 
			{
				m.tell(Message.INVITE_TRAVEL, getSelf());
				System.out.println("Invited " + m.path().name() + "to travel");
			}		
		} 
		else if (message instanceof DeveloperMeeting) 
		{
			secretary = getSender();
			System.out.println("Developer requests meeting");
			DeveloperMeeting dm = (DeveloperMeeting) message;
			meeting = dm.getDevelopers();
			for (ActorRef m : meeting) 
			{
				m.tell(Message.INVITE_TRAVEL, getSelf());
				System.out.println("Invited " + m.path().name() + "to travel");
			} 
		}
		else if ( message instanceof Message )
		{
			Message m = (Message) message;
			switch(m)
			{
				case CUS_ARRIVE:
					arrived++;
					if(arrived == meeting.size()) 
					{
						for (ActorRef c : meeting) 
						{
							System.out.println("Invited " + c.path().name() + " to the meeting");
							c.tell(Message.INVITE_MEETING, getSelf());
						}	
						arrived = 0;
					}
					break;
				case DEV_ARRIVE:
					arrived++;
					if(arrived == meeting.size()) 
					{
						for (ActorRef d : meeting) 
						{
							System.out.println("Invited " + d.path().name() + " to the meeting");
							d.tell(Message.INVITE_MEETING, getSelf());
						}	
						arrived = 0;
					}
					break;					
				case MEETING_ACCEPT:
					inMeeting++;
					if(inMeeting == meeting.size())
					{
						meet();
					}
				default:unhandled(m);
			}
		}
		else
		{
			System.out.println("ERROR: Developer->onReceive - message != instanceof Message");
		}
		
	}
	
	/**
	 * 
	 * @throws InterruptedException
	 */
	public void meet() throws InterruptedException
	{
		int time = (int)(Math.random() * 1000);
		System.out.println(getSelf().path().name() + " meeting");
		Thread.sleep( time );

		for (ActorRef e : meeting)
		{
			e.tell(Message.MEETING_END, getSelf());
		}
		secretary.tell(Message.MEETING_DONE, getSelf());
		inMeeting = 0;
		System.out.println("Nog maar " + inMeeting + " mensen in de vergadering");
	}

	/**
	 * 
	 */
	public void postStop()
	{
		System.out.println("Leader actor exiting");
	}
}
